<template>
    <div class="roles">
        <!-- 面包屑区域 -->
        <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>角色管理</el-breadcrumb-item>
            <el-breadcrumb-item>角色列表</el-breadcrumb-item>
        </el-breadcrumb>

        <!-- 卡片区域 -->
        <el-card>
            <!-- 添加角色按钮区域 -->
            <el-button type='primary' @click="addRolesDialogVisible=true">添加角色</el-button>

            <!-- 表格区域 -->
            <el-table border stripe :data='rolesList'>
                <el-table-column type='expand'>
                    <template slot-scope="scope">
                        <el-row v-for="(item1,i1) in scope.row.children" 
                                :key="item1.id"
                                :class="['bdbottom',i1==0?'bdtop':'','center']">
                            <el-col :span='5'>
                                <el-tag closable
                                        @close='removeById(scope.row,item1.id)'>{{item1.authName}}</el-tag>
                                <i class="el-icon-caret-right"></i>
                            </el-col>
                            <el-col :span='19'>
                                <el-row v-for="(item2,i2) in item1.children" 
                                        :key="item2.id"
                                        :class="[i2===0?'':'bdtop','center']">
                                    <el-col :span='6'>
                                        <el-tag type='success'
                                                closable
                                                @close='removeById(scope.row,item2.id)'>{{item2.authName}}</el-tag>
                                        <i class="el-icon-caret-right"></i>
                                    </el-col>
                                    <el-col :span='18'>
                                        <el-tag type='success'
                                                v-for="(item3) in item2.children"
                                                :key="item3.id"
                                                closable
                                                @close='removeById(scope.row,item3.id)'>
                                            {{item3.authName}}
                                        </el-tag>
                                    </el-col>
                                </el-row>
                            </el-col>
                        </el-row>
                        <!-- <pre>{{scope.row}}</pre> -->
                    </template>
                </el-table-column>
                
                <el-table-column type='index'></el-table-column>
                <el-table-column prop='roleName' label="角色名称"></el-table-column>
                <el-table-column prop='roleDesc' label="角色描述"></el-table-column>
                <el-table-column label="操作">
                    <template slot-scope="scope">
                        <el-button type="primary" icon="el-icon-edit" size='mini' @click="editRoles(scope.row.id)"></el-button>
                        <el-button type="danger" icon="el-icon-delete" size='mini' @click="removeRolesById(scope.row.id)"></el-button>
                        <el-tooltip effect="dark" content="分配角色" placement="top" :enterable='false'>
                            <el-button type="warning" icon="el-icon-setting" size='mini' @click="dialogVisibleShow(scope.row)"></el-button>
                        </el-tooltip>
                        
                    </template>
                </el-table-column>

            </el-table>

            <!-- 添加角色区域 -->
            <el-dialog title="添加角色"
                        :visible.sync="addRolesDialogVisible"
                        width="50%"
                        @close='closeDialogVisible'>
                <el-form :model="addRolesForm" 
                        :rules="addRolesRules" 
                        ref="addRolesForm" 
                        label-width="100px">
                    <el-form-item label="角色名称" prop="roleName">
                        <el-input v-model="addRolesForm.roleName"></el-input>
                    </el-form-item>
                    <el-form-item label="角色描述" prop="roleDesc">
                        <el-input v-model="addRolesForm.roleDesc"></el-input>
                    </el-form-item>
                </el-form>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="addRolesDialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="addRoles">确 定</el-button>
                </span>
            </el-dialog>

            <!-- 编辑角色区域 -->
            <el-dialog title="编辑角色"
                        :visible.sync="editRolesDialogVisible"
                        width="50%"
                        @close='editRolesClose'>
            <el-form :model="editRolesForm" :rules="addRolesRules" ref="editRolesRef" label-width="100px" class="demo-ruleForm">
                <el-form-item label="角色名称" prop="roleName">
                    <el-input v-model="editRolesForm.roleName"></el-input>
                </el-form-item>
                <el-form-item label="角色描述" prop="roleDesc">
                    <el-input v-model="editRolesForm.roleDesc"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editRolesDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="editRolesSubmit">确 定</el-button>
            </span>
            </el-dialog>

            <!-- 分配角色区域 -->
            <el-dialog title="提示"
                    :visible.sync="rolesDialogVisible"
                    width="50%"
                    @close='setRightDialogClosed'>
                    <el-tree :data="rightsList" 
                            :props="treeProps"
                            show-checkbox
                            node-key='id'
                            default-expand-all
                            :default-checked-keys="defKeys"
                            ref="treeRef"></el-tree>
                    <span slot="footer">
                        <el-button @click="rolesDialogVisible = false">取 消</el-button>
                        <el-button type="primary" @click="allotRight">确 定</el-button>
                    </span>
                    </el-dialog>

        </el-card>
    </div>
</template>

<script>
import request from 'network/query'
export default {
   name:'Roles',
   data(){
       return {
           rolesList:[],
           addRolesForm:{
               roleName:'',
               roleDesc:''
           },
           addRolesDialogVisible:false,
           addRolesRules:{
               roleName:[
                   {required:'true',message:'请输入角色名称',trigger:'blur'},
                   {min:3,max:10,message:'长度在3-10个字符之间',trigger:'blur'}
               ],
               roleDesc:[
                    {required:'true',message:'请输入角色描述',trigger:'blur'},
                    {min:3,max:10,message:'长度在3-10个字符之间',trigger:'blur'}
               ]
           },
           editRolesForm:{},
           editRolesDialogVisible:false,
           rolesDialogVisible:false,
           treeProps:{
               children: 'children',
                label: 'authName'
           },
           rightsList:[],
           defKeys:[],
           roleId:''
       }
   },
   created(){
       this.getRolesList()
   },
   methods:{
        // 网络请求方法
       getRolesList(){
           request('roles').then(res=>{
               if(res.meta.status !== 200){
                   return this.$message.error('获取角色列表失败！')
               }
               this.rolesList = res.data
            //    console.log(this.rolesList);
           })
       },

       //添加角色
       addRoles(){
           this.$refs.addRolesForm.validate(valid=>{
               if(!valid) return
               request('roles',{},this.addRolesForm,'post').then(res=>{
                //    console.log(res);
                   if(res.meta.status !== 201){
                       return this.$message.error('添加角色失败')
                   }
                   this.$message.success('添加角色成功~')
                   this.getRolesList()
               })
           })
           this.addRolesDialogVisible = false
       },

    //    编辑角色
        editRoles(id){
            this.editRolesDialogVisible = true 
            console.log(id);
            request('roles/'+id).then(res=>{
                this.editRolesForm = res.data
                console.log(this.editRolesForm);
            })
        },

        // 提交编辑角色
        editRolesSubmit(){
            this.$refs.editRolesRef.validate(valid=>{
                if(!valid) return
                request('roles/'+this.editRolesForm.roleId,{},this.editRolesForm,'put').then(res=>{
                    // console.log(res);
                    if(res.meta.status !== 200){
                        return this.$message.error('修改角色失败！')
                    }
                    this.$message.success('修改角色成功~')
                    this.getRolesList()
                })
                // request('roles/'+this.editRolesForm.roleId,{},{
                //     roleName:this.editRolesForm.roleName,
                //     roleDesc:this.editRolesForm.roleDesc
                // },'put').then(res=>{
                //     console.log(res);
                //     if(res.meta.status !== 200){
                //         return this.$message.error('修改角色失败！')
                //     }
                //     this.$message.success('修改角色成功~')
                //     this.getRolesList()
                // })
            })
            this.editRolesDialogVisible = false
        },

        // 删除角色
        async removeRolesById(id){
            const confirmResult = await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).catch(err => err)
            if(confirmResult !== 'confirm'){
                return this.$message.info('已取消删除！')
            }
            request('roles/'+id,{},{},'delete').then(res=>{
                console.log(res);
                this.$message.success('删除角色成功~')
                this.getRolesList()
            })
        },

        // 删除权限
        async removeById(role,rightId){
            const confirmResult = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).catch(err => err)
            if(confirmResult!=='confirm'){
                this.$message.error('已取消删除')
            }
            request(`roles/${role.id}/rights/${rightId}`,{},{},'delete').then(res=>{
                console.log(res);
                this.$message.success('删除权限成功~')
                role.children = res.data
            })
        },

        // 事件点击方法
        closeDialogVisible(){
            this.$refs.addRolesForm.resetFields()
        },
        
        editRolesClose(){
            this.$refs.editRolesRef.resetFields()
        },

        dialogVisibleShow(role){
            this.roleId = role.id
            // 分配角色所有权限列表
            request('rights/tree').then(res=>{
                console.log(res);
                this.rightsList = res.data
                this.getLeafKeys(role,this.defKeys)
            }),
            this.rolesDialogVisible = true
        },

        getLeafKeys(node,arr){
            if(!node.children){
                return arr.push(node.id)
            }
            node.children.forEach(item =>{
                this.getLeafKeys(item,arr)
            })
        },

        setRightDialogClosed(){
            this.defKeys = []
        },

        allotRight(){
            const keys = [
                ...this.$refs.treeRef.getCheckedKeys(),
                ...this.$refs.treeRef.getHalfCheckedKeys()
            ]
            console.log(keys);
            const strId = keys.join(',')
            request(`roles/${this.roleId}/rights`,{},{rids:strId},'post').then(res=>{
                console.log(res);
                if(res.meta.status !== 200){
                    this.$message.error('分配角色权限失败')
                }
                this.$message.success('分配角色权限成功~')
                this.getRolesList()
            })
            this.rolesDialogVisible = false
        }
   }
};
</script>

<style scoped>
    .el-tag{
        margin: 15px;
    }

    .bdtop{
        border-top: 1px solid #eee;
    }

    .bdbottom{
        border-bottom: 1px solid #eee;
    }
    .center{
        display: flex;
        align-items: center;
    }
</style>
